package com.posjiajia.user.core.bo;

import com.alibaba.fastjson.JSONObject;
import com.posjiajia.commom.utils.MD5Util;
import com.posjiajia.commom.utils.exceptions.ServiceRuntimeException;
import com.posjiajia.commom.utils.vo.result.BaseResult;
import com.posjiajia.user.core.dao.UserDao;
import com.posjiajia.user.core.params.UserQueryParam;
import com.posjiajia.user.core.po.DevicePo;
import com.posjiajia.user.core.po.OrganPo;
import com.posjiajia.user.core.po.UserLoginLogPo;
import com.posjiajia.user.core.po.UserPo;
import com.posjiajia.user.core.utils.BeanTransferUtil;
import com.posjiajia.user.core.vo.OrganVo;
import com.posjiajia.user.core.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

/**
 * @ClassName UserBo
 * @Description 用户业务实现
 *
 * @author sunhaojie 3113751575@qq.com
 * @date 2016年8月23日 下午11:37:52
 */
@Service
public class UserBo {

	private static final Logger logger = LoggerFactory.getLogger(UserBo.class);

	private final static Map<String, UserVo> sessionMap = new HashMap<String, UserVo>();

	@Autowired
	private UserDao userDao;

	@Autowired
	private SequenceBo sequenceBo;

	@Autowired
	private UserLoginLogBo userLoginBo;

	@Autowired
	private OrganBo organBo;

	@Autowired
	private DeviceBo deviceBo;

	/**
	 * 
	 * @Title login
	 * @Description 根据用户身份和密码验证是否为用户本人
	 * @param pin 用户邮箱或者手机号
	 * @param password 用户密码不可逆密文
	 * @return
	 *
	 * @author sunhaojie 3113751575@qq.com
	 * @date 2016年8月23日 下午11:42:59
	 */
	public UserVo login(String pin, String password, UserLoginLogPo userLoginLogPo) {

		UserPo po = userDao.queryUserByPinAndPwd(pin,MD5Util.md5(password));
		if (po == null){
			throw new ServiceRuntimeException("LOGIN_FAIL");
		}
		if (po.getStatus() == 1){
			throw new ServiceRuntimeException("STATUS_ERROR");
		}
		String userToken = UUID.randomUUID().toString();
		UserVo userVo = BeanTransferUtil.transferType(po,UserVo.class);
		userVo.setUserToken(userToken);
		// 设置base组织信息
		OrganPo organPo = organBo.queryByOrganId(userVo.getOrganId());
		userVo.setOrganName(organPo.getName());

		// 设置top组织信息
		OrganVo topOrgan = organBo.queryTopOrgan(userVo.getOrganId());
		userVo.setParentOrganId(topOrgan.getOrganId());
		userVo.setParentOrganName(topOrgan.getName());

		sessionMap.put(userToken, userVo);

		if (userLoginLogPo != null) {
			userLoginLogPo.setUserId(userVo.getUserId());
			userLoginLogPo.setUserToken(userToken);
 			createLoginLog(userLoginLogPo);
		}
		return userVo;
	}

	/**
	 * 记录登录日志
	 */
	private void createLoginLog(UserLoginLogPo po) {
//		po.setIp(requestIp);
//		po.setMac(getMac(requestIp));
//		po.setUserId(userVo.getUserId());
//		po.setUserToken(userVo.getUserToken());
//		try {
//			Properties props = System.getProperties();
//			po.setOsName(props.getProperty("os.name"));
//			po.setOsVersion(props.getProperty("os.version"));
//		}catch (Exception e){
//			logger.error("get login log error",e);
//		}
		try {
			po.setRequestServer(InetAddress.getLocalHost().getHostAddress().toString());
		} catch (UnknownHostException e) {
			logger.error("get login log error",e);
		}
		DevicePo devicePo = deviceBo.selectByMac(po.getMac());

		if (devicePo != null) {
			logger.info(JSONObject.toJSONString(devicePo));
			po.setTopOrganId(String.valueOf(devicePo.getTopOrganId()));
			po.setBaseOrganId(String.valueOf(devicePo.getBaseOrganId()));
		} else {
			logger.info(po.getMac() + "没有找到对应的设备信息");
		}
		po.setLoginTime(new Date());
		userLoginBo.insert(po);
	}

	/**
	 * 通过IP地址获取MAC地址
	 * @param ip
	 * @return mac
	 */
	public String getMac(String ip){
		String mac = "";
		try {
			Process p = Runtime.getRuntime().exec("arp -n");
			InputStreamReader ir = new InputStreamReader(p.getInputStream());
			LineNumberReader input = new LineNumberReader(ir);
			p.waitFor();
			boolean flag = true;
			String ipStr = "(" + ip + ")";
			while(flag) {
				String str = input.readLine();
				if (str != null) {
					if (str.indexOf(ipStr) > 1) {
						int temp = str.indexOf("at");
						mac = str.substring(
								temp + 3, temp + 20);
						break;
					}
				} else
					flag = false;
			}
		} catch (Exception e) {
			logger.error("get mac error",e);
		}
		return mac;
	}

	/**
	 * 用户注册
	 */
	public BaseResult userRegister(UserVo vo){
		vo.setUserId(getUserSerNo());
		UserPo po = BeanTransferUtil.transferType(vo,UserPo.class);
		po.setPassword(MD5Util.md5(vo.getPassword()));
		po.setAdmin(vo.getIsAdmin().equals("1")?true:false);
		po.setStatus(0);
		userDao.insert(po);
		logger.info("user register success,userId:{}",vo.getUserId());
		return BaseResult.SUCCESS;
	}

	/**
	 * 取序列的值
	 * @return
     */
	private Long getUserSerNo() {
		return sequenceBo.getNextUserId();
	}

	/**
	 * 通过token取用户
	 * @param userToken
	 * @return
     */
	public UserVo getUserByToken(String userToken) {
		return sessionMap.get(userToken);
	}

	public List<UserVo> query(UserQueryParam userQueryParam) {
		UserPo userPo = BeanTransferUtil.transferType(userQueryParam,UserPo.class);
		userPo.setEmail(userQueryParam.getPin());
//		userPo.setMobilePhoneNo(userQueryParam.getPin());
		if (!StringUtils.isEmpty(userQueryParam.getOrganId())) {
			userPo.setOrganId(Integer.parseInt(userQueryParam.getOrganId()));
		}
		List<UserPo> userPoList = userDao.queryUser(userPo);
		List<UserVo> userVoList = BeanTransferUtil.batchTransferType(userPoList,UserVo.class);
		for (UserVo userVo : userVoList){
			for (UserPo po : userPoList){
				if (userVo.getUserId().longValue()==po.getUserId()){
					userVo.setIsAdmin(po.getAdmin()==true?"1":"0");
				}
			}
			if (userVo != null && userVo.getOrganId() != null){
				OrganPo organPo = organBo.queryByOrganId(userVo.getOrganId());
				userVo.setOrganName(organPo == null?"":organPo.getName());
				if (organPo != null && organPo.getParentOrganId() != null){
					OrganPo genOrgan = getRootOrgan(organPo);
					userVo.setParentOrganId(genOrgan==null?null:genOrgan.getOrganId());
					userVo.setParentOrganName(genOrgan == null?"":genOrgan.getName());
				}
			}
		}
		return userVoList;
	}

	/**
	 * 递归获取organPo 的根组织
	 * @param organPo
	 * @return
     */
	private OrganPo getRootOrgan(OrganPo organPo) {
		OrganPo rootOrgan = organBo.queryByOrganId(organPo.getParentOrganId());
		if (rootOrgan != null && rootOrgan.getParentOrganId() != null){
			return getRootOrgan(rootOrgan);
		}else {
			return rootOrgan;
		}
	}

	/**
	 * 修改用户状态
	 * @param userId
     */
	public void delete(String userId) {
		UserPo po = getUserById(Long.parseLong(userId));
		if (po.getStatus() == 0){
			po.setStatus(1);
		}else {
			po.setStatus(0);
		}
		userDao.updateUser(po);
	}

	private UserPo getUserById(Long userId) {
		return userDao.get(userId);
	}

	public UserVo getUserById(String userId){
		UserPo userPo = getUserById(Long.valueOf(userId));
		if (userPo == null){
			return null;
		}
		return BeanTransferUtil.transferType(userPo,UserVo.class);
	}

	/**
	 * 根据用户标识查询用户
	 * @param pin
	 * @return
     */
	public UserPo getUserByPin(String pin) {
		return userDao.getUserByPin(pin);
	}

	/**
	 * 更新用户
	 * @param userVo
     */
	public void updateUser(UserVo userVo) {
		UserPo po = getUserById(userVo.getUserId());
		po.setAdmin(userVo.getIsAdmin().equals("1")?true:false);
		po.setMobilePhoneNo(userVo.getMobilePhoneNo());
		po.setEmail(userVo.getEmail());
		po.setOrganId(userVo.getOrganId());
		userDao.updateUser(po);
	}
}
